#!/bin/env python
# -*- coding: UTF-8 -*-

import urllib2
import socket
import httplib
from proxycfg import *


def verify(host = "localhost", port = "", protocol = "http", username = "", password = "", timeout = 30, retry = 2, verified = set()):
    #proxy=urllib2.ProxyHandler({'https': 'http://lk:2002@172.17.5.53:80'})
    proxyurl = (username + (":" + password if password != "" else "") + "@" if
            username != "" else "") + host + ( ":" + str(port) if port != "" else "")
    #print proxyurl
    proxyhandler = urllib2.ProxyHandler({protocol : proxyurl})
    proxyopener = urllib2.build_opener(proxyhandler)
    errors = set()
    for verify_site in verify_sites:
        if verify_site in verified:
            continue
        try:
            response = proxyopener.open(verify_site, timeout = timeout)
            #print response.code
            if response.code != 200:
                errors.add("Fail")
            else:
                verified.add(verify_site)
                #print verify_site, "is ok"
        except socket.timeout:
            errors.add("TimeOut")
        except urllib2.URLError:
            # open https site timeout
            errors.add("URLError")
        except httplib.BadStatusLine:
            # proxy not support https
            errors.add("BadStatusLine")
    if "TimeOut" in errors:
        if retry == 1:
            return "fail"
        return verify(host, port, protocol, username, password, timeout, retry-1,  verified)
    if "Fail" not in errors:
        if "URLError" not in errors and "BadStatusLine" not in errors:
            return "https"
        else:
            return "http"



if __name__ == "__main__":
    #verify(host = "192.168.1.131", port = 8080, protocol = 'https')
    #verify(host = "82.127.91.227", port = 80, protocol = 'http')
    print verify(host = "23.21.156.198", port = 443, protocol = 'http')
